#include "qrsagsmapswipetool.h"
#include "qgsmapmouseevent.h"
#include "qgslayertreenode.h"
#include "qgslayertreemodel.h"

QRSAGSMapSwipeTool::QRSAGSMapSwipeTool(QgsMapCanvas *mapCanvas, QgsLayerTreeView *layerTreeVeiw)
    : QgsMapTool(mapCanvas)
{
    this->mMapCanvas = mapCanvas;
    this->mLayerTreeView = layerTreeVeiw;
    this->mMapSwipe = new QRSAGSMapSwipe(this->mMapCanvas);
    this->mCursorV = QCursor(Qt::SplitVCursor);
    this->mCursorH = QCursor(Qt::SplitHCursor);
    this->hasSwipe = false;

}

QRSAGSMapSwipeTool::~QRSAGSMapSwipeTool()
{
    delete this->mMapSwipe;
    delete this->mMapCanvas;
    delete this->mLayerTreeView;
}

void QRSAGSMapSwipeTool::activateConnect()
{
    connect(this->mMapCanvas, &QgsMapCanvas::mapCanvasRefreshed, this, &QRSAGSMapSwipeTool::setMap);
    connect(this->mLayerTreeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QRSAGSMapSwipeTool::setLayerSwipe);
    connect(QgsProject::instance(), &QgsProject::removeAll, this, &QRSAGSMapSwipeTool::disable);
}

void QRSAGSMapSwipeTool::deactivateConnect()
{
    disconnect(this->mMapCanvas, &QgsMapCanvas::mapCanvasRefreshed, this, &QRSAGSMapSwipeTool::setMap);
    disconnect(this->mLayerTreeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QRSAGSMapSwipeTool::setLayerSwipe);
    disconnect(QgsProject::instance(), &QgsProject::removeAll, this, &QRSAGSMapSwipeTool::disable);
}

void QRSAGSMapSwipeTool::activate()
{
    this->mMapCanvas->setCursor(QCursor(Qt::PointingHandCursor));
    //建立信号与槽的连接
    this->activateConnect();
    this->hasSwipe = false;
    this->disableSwipe = false;
    this->setLayerSwipe();
}

void QRSAGSMapSwipeTool::deactivate()
{
    emit(this->deactivated());
    this->mMapSwipe->clear();
    this->deactivateConnect();
}

void QRSAGSMapSwipeTool::canvasPressEvent(QgsMapMouseEvent *event)
{
    bool checkLayer = (this->mMapSwipe->mMapLayers.size() != 0);
    if(checkLayer){
        this->hasSwipe = true;
        this->mFirstPoint.setX(event->x());
        this->mFirstPoint.setY(event->y());
        this->checkDirection = true;
    }
}

void QRSAGSMapSwipeTool::canvasReleaseEvent(QgsMapMouseEvent *event)
{
    this->hasSwipe = false;
    this->mMapCanvas->setCursor(QCursor(Qt::PointingHandCursor));
}

void QRSAGSMapSwipeTool::canvasMoveEvent(QgsMapMouseEvent *event)
{
    if(this->hasSwipe){
        if(this->checkDirection){
            int dX = abs(event->x() - this->mFirstPoint.x());
            int dY = abs(event->y() - this->mFirstPoint.y());
            bool isVertical = dX > dY;
            this->mMapSwipe->setIsVertical(isVertical);
            this->checkDirection = false;
            this->mMapCanvas->setCursor(isVertical?this->mCursorH:this->mCursorV);
        }
        this->mMapSwipe->setLength(event->x(), event->y());
    }
}

void QRSAGSMapSwipeTool::setLayerSwipe()
{
    if(this->disableSwipe){
        return;
    }

    //如果选中的第一个图层没有勾选显示的话，需要提醒勾选显示
    QModelIndex currentIndex = this->mLayerTreeView->currentIndex();
    QgsLayerTreeNode *layerTreeNode = this->mLayerTreeView->layerTreeModel()->index2node(currentIndex);
    if(!layerTreeNode->itemVisibilityChecked()){
        QMessageBox::information(new QWidget(), tr("Warm Tips"), tr("If you want to swipe with this maplayer, please to check it..."));
        return;
    }

    QList<QgsMapLayer*> mapLayers;
    if(layerTreeNode->inherits("QgsLayerTreeLayer")){
        QgsLayerTreeLayer *layerTreeLayer = (QgsLayerTreeLayer*)layerTreeNode;
        QgsMapLayer *layer = layerTreeLayer->layer();

        if(!layer->isSpatial()){
            return;
        }

        mapLayers.append(layer);
        qDebug() << "=============001===" << mapLayers.size();

    }else {
        QgsLayerTreeGroup *layerTreeGroup = this->mLayerTreeView->currentGroupNode();
        if(layerTreeGroup->parent() == nullptr){
            return;
        }
        QList<QgsLayerTreeLayer *> layerTreeLayers = layerTreeGroup->findLayers();
        QList<QgsLayerTreeLayer *> layerTreeLayersTemp;
        for(QgsLayerTreeLayer *layerTreeLayer: layerTreeLayers){
            if(layerTreeLayer->itemVisibilityChecked()){
                layerTreeLayersTemp.append(layerTreeLayer);
                mapLayers.append(layerTreeLayer->layer());
            }
        }
        if(layerTreeLayersTemp.size() == 0){
            return;
        }
        qDebug() << "=============002===" << mapLayers.size();
    }

    this->mMapSwipe->clear();
    this->mMapSwipe->setLayers(mapLayers);
    this->setMap();
}

void QRSAGSMapSwipeTool::disable()
{
    this->mMapSwipe->clear();
    this->hasSwipe = false;
    this->disableSwipe = true;
}

void QRSAGSMapSwipeTool::setMap()
{
    if(this->mMapSwipe->getMapLayers().size() == 0){
        return;
    }

    QgsMapSettings settings = this->mMapCanvas->mapSettings();
    settings.setLayers(this->mMapSwipe->getMapLayers());
    settings.setBackgroundColor(QColor(Qt::transparent));

    this->mMapSwipe->setRect(this->mMapCanvas->extent());

    QgsMapRendererParallelJob *job = new QgsMapRendererParallelJob(settings);
    job->start();
    connect(job, &QgsMapRendererParallelJob::finished, this, [=](){
        QImage image = job->renderedImage();
        if(this->mMapCanvas->property("retro").toBool()){
            image = image.scaled(image.width()/3, image.height()/3);
            image = image.convertToFormat(QImage::Format_Indexed8, Qt::OrderedDither | Qt::OrderedAlphaDither);
        }
        this->mMapSwipe->setImage(image);
        qDebug() << "=============003";
    });
    job->waitForFinished();
}
